package com.htpay.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.htpay.aspect.AutoLog;
import com.htpay.model.common.Constant;
import com.htpay.model.common.ResponseBean;
import com.htpay.model.entity.Merchant;
import com.htpay.model.entity.MerchantWalletInfo;
import com.htpay.service.IMerchantService;
import com.htpay.service.IMerchantWalletService;
import com.htpay.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/settings")
@Slf4j
public class SettingController {

    @Autowired
    IMerchantService merchantService;

    @Autowired
    IMerchantWalletService merchantWalletService;

    @AutoLog(value = "修改登录密码")
    @PostMapping(value = "/account/updatePwd")
    public ResponseBean modifyPwd(@RequestBody JSONObject jsonObject, HttpServletRequest req) {
        ResponseBean bean = new ResponseBean();

        //获取旧密码
        String oldPwd = jsonObject.getString("old_password");
        if (ObjectConvertUtils.isEmpty(oldPwd)) {
            return bean.error("账户旧密码不能为空");
        }

        //获取新密码
        String newPwd = jsonObject.getString("new_password");
        if (ObjectConvertUtils.isEmpty(newPwd)) {
            return bean.error("账户新密码不能为空");
        }

        //获取确认新密码
        String confirmPwd = jsonObject.getString("confirm_password");
        if (ObjectConvertUtils.isEmpty(confirmPwd)) {
            return bean.error("账户确认新密码不能为空");
        }

        if (!newPwd.equals(confirmPwd)) {
            return bean.error("新密码两次不一致");
        }

        //密码8-12位，且需同时含有字母和数字
        //不满足该正则，会被排除
        if (!ToolUtil.isLetterDigit(newPwd)) {
            return bean.error("新密码由8-12位数字、字母组成");
        }

        try {
            Integer merchantId = MerchantUtil.getMerchantId(req);
            Merchant merchant = merchantService.getById(merchantId);
            if (merchant == null) return bean.error("token非法无效");

            String originPwd = merchant.getPassword();
            String account = merchant.getLoginName();

            //加密提交的旧密码，需要凭此验证是否合法
            String submitOldPwd = PasswordUtil.encrypt(account, oldPwd, merchant.getSalt());
            log.info("==== 获取当前修改密码[" + originPwd + "], 提交的密码[" + submitOldPwd + "] ====");

            if (!originPwd.equals(submitOldPwd)) {
                return bean.error("旧密码不正确");
            }

            String newEncryptPwd = PasswordUtil.encrypt(account, confirmPwd, merchant.getSalt());
            merchantService.updatePassword(merchantId, newEncryptPwd);

            //清空用户登录Token缓存
            JedisUtil.delKey(Constant.PREFIX_SHIRO_REFRESH_TOKEN + account);
            //清空商户ID信息
            JedisUtil.delKey(Constant.SYS_USER_INFO + account);
        } catch (Exception e) {
            return bean.error(e.getMessage());
        }

        return bean.success("修改密码成功");
    }

    @AutoLog(value = "修改提现密码")
    @PutMapping(value = "/withdraw/updatePwd")
    public ResponseBean modifyWithdrawPwd(@RequestBody JSONObject jsonObject, HttpServletRequest req) {
        ResponseBean bean = new ResponseBean();

        String phone = jsonObject.getString("mobile");
        if (ObjectConvertUtils.isEmpty(phone)) {
            return bean.error("手机号码为空");
        }

        if (phone.length() != 11) return bean.error("手机号为非标准11位号码");

        String smsCode = jsonObject.getString("smscode");
        if (ObjectConvertUtils.isEmpty(smsCode)) {
            return bean.error("短信验证码为空");
        }

        ///判断短信验证码是否正确
        Object code = JedisUtil.getObject(phone);
        if (!smsCode.equals(code)) {
            log.error("--- 手机验证码【" + smsCode + "】错误,正确验证码【" + code + "】 ---");
            return bean.error("短信验证码无效");
        }

        //获取旧密码
        String oldPwd = jsonObject.getString("old_password");
        if (ObjectConvertUtils.isEmpty(oldPwd)) {
            return bean.error("账户旧密码不能为空");
        }

        //获取新密码
        String newPwd = jsonObject.getString("new_password");
        if (ObjectConvertUtils.isEmpty(newPwd)) {
            return bean.error("账户新密码不能为空");
        }

        //新密码长度校验
        if (!ToolUtil.isDigitFixedLength(newPwd, 6)) {
            return bean.error("新密码由6位数字、字母组成");
        }

        //获取确认新密码
        String confirmPwd = jsonObject.getString("confirm_password");
        if (ObjectConvertUtils.isEmpty(confirmPwd)) {
            return bean.error("账户确认新密码不能为空");
        }

        if (!newPwd.equals(confirmPwd)) {
            return bean.error("新密码两次不一致");
        }

        try {
            Integer merchantId = MerchantUtil.getMerchantId(req);
            String account = MerchantUtil.getAccountName(req);
            MerchantWalletInfo merchantWalletInfo = merchantWalletService.getWalletInfoByMerchantId(merchantId);
            String currentPwd = merchantWalletInfo.getWithdrawPassword();
            String submitValidatePwd = PasswordUtil.encrypt(account, oldPwd, merchantWalletInfo.getWithdrawSalt());
            log.info("==== 获取到当前用户[" + account + "]余额提现的密码为[" + currentPwd + "], 待验证的密码为[" + submitValidatePwd + "] ====");

            if (!submitValidatePwd.equals(currentPwd)) {
                return bean.error("旧密码不正确");
            }

            String newEncryptPwd = PasswordUtil.encrypt(account, confirmPwd, merchantWalletInfo.getWithdrawSalt());
            merchantWalletService.updateWithdrawPwd(merchantId, newEncryptPwd);
        } catch (Exception e) {
            return bean.error(e.getMessage());
        }

        return bean.success("密码修改成功");
    }

    @AutoLog("忘记密码修改")
    @PostMapping(value = "/forgotPwd/update")
    public ResponseBean forgetPwdUpdate(@RequestBody JSONObject jsonObject, Merchant merchant) {
        ResponseBean bean = new ResponseBean();

        String account = jsonObject.getString("username");
        if (ObjectConvertUtils.isEmpty(account)) {
            return bean.error("用户名为空");
        }

        String phone = jsonObject.getString("phone");
        if (ObjectConvertUtils.isEmpty(phone)) {
            return bean.error("手机号为空");
        }

        if (phone.length() != 11) {
            return bean.error("手机号格式错误");
        }

        String smsCode = jsonObject.getString("smscode");
        if (ObjectConvertUtils.isEmpty(smsCode)) {
            return bean.error("短信验证码为空");
        }

        //获取新密码
        String newPwd = jsonObject.getString("new_password");
        if (ObjectConvertUtils.isEmpty(newPwd)) {
            return bean.error("账户新密码不能为空");
        }

        //新密码长度校验
        if (!ToolUtil.isLetterDigit(newPwd)) {
            return bean.error("新密码由8-12位数字、字母组成");
        }

        //获取确认新密码
        String confirmPwd = jsonObject.getString("confirm_password");
        if (ObjectConvertUtils.isEmpty(confirmPwd)) {
            return bean.error("账户确认新密码不能为空");
        }

        if (!newPwd.equals(confirmPwd)) {
            return bean.error("新密码两次不一致");
        }

        ///判断短信验证码是否正确
        Object code = JedisUtil.getObject(phone);
        if (!smsCode.equals(code)) {
            log.error("--- 手机验证码【" + smsCode + "】错误,正确验证码【" + code + "】 ---");
            return bean.error("手机验证码无效");
        }

        try {
            merchant.setLoginName(account);
            merchant.setPhone(phone);

            Merchant user = merchantService.getOne(new QueryWrapper<Merchant>(merchant));
            if (user != null) {
                String salt = user.getSalt();
                String newEncryptPwd = PasswordUtil.encrypt(account, confirmPwd, salt);
                log.info("==== [" + account + "]忘记密码，修改新密码[" + newEncryptPwd + "] ====");
                merchantService.updatePassword(user.getMerchantId(), newEncryptPwd);
                return bean.success("修改密码成功");
            }

        } catch (Exception e) {
            log.info(e.getMessage());
            return bean.error(e.getMessage());
        }

        return bean.error("该账号未注册");
    }
}
